package com.shadow.cloud.dap7.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shadow.cloud.common.constants.SysConstants;
import com.shadow.cloud.dap7.bo.DictionaryQuery;
import com.shadow.cloud.dap7.entity.Dictionary;
import com.shadow.cloud.dap7.mapper.DictionaryMapper;
import com.shadow.cloud.data.RedisCacheHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * 数据字典 服务实现类.
 */
@Slf4j
@Service
public class DictionaryService extends ServiceImpl<DictionaryMapper, Dictionary> implements IService<Dictionary> {

    @Resource
    private DictionaryMapper dictionaryMapper;
    @Resource
    private RedisCacheHelper redisCacheHelper;

    /**
     * 保存字典信息.
     *
     * @param dictionary 字典信息
     * @return 数据变化量
     **/
    @Transactional(rollbackFor = Exception.class)
    public int saveDictionary(final Dictionary dictionary) {
        //新增并更新缓存
        int insert = dictionaryMapper.insert(dictionary);
        updateCache(dictionary.getParentId());
        return insert;
    }

    /**
     * 通过ID删除字典项.
     *
     * @param id 字典ID
     * @return 数据变化量
     **/
    @Transactional(rollbackFor = Exception.class)
    public int delete(final String id) {
        final Dictionary item = getById(id);
        if (item != null) {
            // 删除并更新缓存
            int delete = dictionaryMapper.deleteById(id);
            updateCache(item.getParentId());
            return delete;
        }
        return 0;
    }

    /**
     * 更新字典信息
     *
     * @param dictionary 字典信息
     * @return 数据变化量
     **/
    @Transactional(rollbackFor = Exception.class)
    public int update(final Dictionary dictionary) {
        //修改并更新缓存
        int update = dictionaryMapper.updateById(dictionary);
        updateCache(dictionary.getParentId());
        return update;
    }

    /**
     * 分页查询字典
     *
     * @param dictionaryQuery 字典查询对象
     * @return boolean
     **/
    public IPage<Dictionary> getDictionaryList(final DictionaryQuery dictionaryQuery) {
        final Page<Dictionary> page = new Page<>(dictionaryQuery.getPage(), dictionaryQuery.getLimit());
        final LambdaQueryWrapper<Dictionary> wrapper = new LambdaQueryWrapper<Dictionary>()
                .eq(StringUtils.isNotBlank(dictionaryQuery.getParentId()), Dictionary::getParentId, SysConstants.PARENT_ID)
                .like(StringUtils.isNotBlank(dictionaryQuery.getDictName()), Dictionary::getDictName, dictionaryQuery.getDictName());
        return dictionaryMapper.selectPage(page, wrapper);
    }

    /**
     * 判断字典值是否存在.
     *
     * @param name     字典名称
     * @param value    字典值
     * @param parentId 上级字典ID
     * @return boolean
     **/
    public boolean isExists(String name, String value, String parentId) {
//        boolean existsFlag = false;
//        QueryWrapper<Dictionary> dictionaryWrapper = new QueryWrapper<>();
//        dictionaryWrapper.eq(name, value);
//        dictionaryWrapper.eq(PARENT_ID, parentId);
//        List<Dictionary> dictList = list(dictionaryWrapper);
//        if (CollectionUtils.isNotEmpty(dictList)) {
//            existsFlag = true;
//            if (StringUtils.isNotBlank(id) && id.equals(dictList.get(0).getId())) {
//                existsFlag = false;
//            }
//        }
//        return existsFlag;
        return false;
    }

    /**
     * 获取字典项根据上级ID和字典值.
     * @date 15:55 2020/9/8
     * @param value 字典值
     * @param parentId 上级字典ID
     * @return net.zoneland.demo.dal.entity.sys.Dictionary
     **/
    public Dictionary getByValue(final String parentId, final String value) {
//        QueryWrapper<Dictionary> dictionaryWrapper = new QueryWrapper<>();
//        dictionaryWrapper.eq(PARENT_ID, parentId);
//        dictionaryWrapper.eq("dict_value", value);
//        List<Dictionary> list = list(dictionaryWrapper);
//        if (CollectionUtils.isNotEmpty(list)) {
//            return list.get(0);
//        }
        return null;
    }

    /**
     * 获取字典项根据上级ID和名称.
     * @date 15:55 2020/9/8
     * @param name 字典名称
     * @param parentId 上级字典ID
     * @return net.zoneland.demo.dal.entity.sys.Dictionary
     **/
    public Dictionary getByName(final String parentId, final String name) {

//        QueryWrapper<Dictionary> dictionaryWrapper = new QueryWrapper<>();
//        dictionaryWrapper.eq(PARENT_ID, parentId);
//        dictionaryWrapper.eq("dict_name", name);
//        return Optional.ofNullable(list(dictionaryWrapper)).filter(CollectionUtils::isNotEmpty)
//            .map(list -> list.stream().findFirst().get()).orElse(null);
        return null;
    }

    /**
     * 获取缓存的字典列表根据上级ID.
     * @date 15:55 2020/9/8
     * @param parentId 上级字典ID
     * @return java.util.List
     **/
    public List<Dictionary> getByParentId(final String parentId) {
        return Collections.unmodifiableList(getCacheItems(parentId));
    }

    /**
     * 获取最新的字典列表（不走缓存）根据上级ID.
     * @author pbody
     * @date 15:55 2020/9/8
     * @param parentId 上级字典ID
     * @return java.util.List
     **/
    public List<Dictionary> getByParentIdNow(final String parentId) {
//        final QueryWrapper<Dictionary> dictionaryWrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(parentId)) {
//            dictionaryWrapper.eq(PARENT_ID, parentId);
//        }
//        dictionaryWrapper.orderByAsc("parent_id,orders");
//        return Collections.unmodifiableList(list(dictionaryWrapper));
        return null;
    }

    /**
     * 从缓存中获取字典数据：若从redis读取失败则从数据库中获取.
     * @date 15:57 2020/9/8
     * @param parentId 上级编码
     * @return java.util.List
     **/
    public List<Dictionary> getCacheItems(final String parentId) {
//        try {
//            final String dicJson =  redisCacheHelper.hGet(CacheEnum.DICT_CACHE_PREFIX.getValue(), parentId);
//            //先从缓存中胡获取数据字典
//            if (StringUtils.isNotBlank(dicJson)) {
//                return JacksonUtils.toTypeObject(dicJson, new TypeReference<List<Dictionary>>() { });
//            }
//            log.info("{}的缓存读取为空：{}", CacheEnum.DICT_CACHE_PREFIX.getValue(), parentId);
//        } catch (JsonProcessingException e) {
//            log.error("获取缓存数据转换出错", e);
//        }
//        return getByParentIdNow(parentId);
        return null;
    }

    /**
     * 更新数据字典缓存.
     * @date 16:09 2020/9/8
     * @param parentId 上级字典编码ID
     **/
    private void updateCache(final String parentId) {
//        try {
//            redisCacheHelper.hSet(CacheEnum.DICT_CACHE_PREFIX.getValue(), parentId,
//                JacksonUtils.toJsonString(getByParentIdNow(parentId)), NEVER_TIME_OUT);
//        } catch (JsonProcessingException e) {
//            LOGGER.error("更新时缓存数据对象转换异常", e);
//        }
    }

    /**
     * 第一次启动加载数据字典缓存，以parentId进行分组存储.
     * @Date 16:09 2020/9/8
     **/
    public void initAllCache() {
//        final QueryWrapper<Dictionary> dictionaryWrapper = new QueryWrapper<>();
//        dictionaryWrapper.orderByAsc("parent_id,orders");
//        Optional.ofNullable(list(dictionaryWrapper)).filter(CollectionUtils::isNotEmpty)
//            .ifPresent(items -> saveCacheByParentId(items));
    }

    /**
    * 初始保存所有字典缓存.
    * @date 2:21 PM 2022/9/7
    * @param itemList 数据列表
    **/
    private void saveCacheByParentId(final List<Dictionary> itemList) {
//        final Map<String, List<Dictionary>> dictDataMap = new HashMap<>();
//        itemList.stream().forEach(dictItem -> {
//            final List<Dictionary> typeList = dictDataMap.get(dictItem.getParentId());
//            if (CollectionUtils.isNotEmpty(typeList)) {
//                typeList.add(dictItem);
//            } else {
//                //parentId第一个put进行
//                final List<Dictionary> newDicList = new ArrayList<>();
//                newDicList.add(dictItem);
//                dictDataMap.put(dictItem.getParentId(), newDicList);
//            }
//        });
//        //根据上级ID分类存储
//        final Iterator<?> iterator = dictDataMap.entrySet().iterator();
//        while (iterator.hasNext()) {
//            Map.Entry<String, List<Dictionary>> entry = (Map.Entry<String, List<Dictionary>>) iterator.next();
//            // 放入cache缓存
//            try {
//                redisCache.hset(CacheEnum.DICT_CACHE_PREFIX.getValue(), entry.getKey(),
//                    JacksonUtils.toJsonString(entry.getValue()), NEVER_TIME_OUT);
//            } catch (JsonProcessingException e) {
//                LOGGER.error("加载数据字典写入缓存失败", e);
//            }
//        }
    }
}
